﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.RisServer.Abstractions;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Controllers;

[Authorize]
public class ExamEventController(IRepository<Exam, Guid> examRepository, IExamPermissionService examPermissionService) : AbpControllerBase
{
    private readonly IRepository<Exam, Guid> _examRepository = examRepository;
    private readonly IExamPermissionService _examPermissionService = examPermissionService;

    [HttpGet("api/exam-event/get-exam-events")]
    public async Task<IActionResult> GetExamEvents([FromQuery] Guid examId)
    {
        try
        {
            var exam = await _examRepository.GetAsync(examId);
            await _examPermissionService.IsValidAsync(exam, true);
            return Ok(new
            {
                Success = true,
                Data = new
                {
                    Columns = new object[]
                    {
                        new { DataField="oid", Caption="", visible=false },
                        new { DataField="eventType", Caption="事件类型" },
                        new { DataField="eventTime", Caption="事件时间",DataType="datetime" },
                        new { DataField="operatorName", Caption="操作人",Width=100 },
                        new { DataField="eventContent", Caption="备注",Width=250 }
                    },
                    Rows = exam.ExamEvents.OrderBy(e => e.CreationTime).Select(e => new
                    {
                        e.Oid,
                        e.EventType,
                        e.EventContent,
                        e.EventTime,
                        OperatorName = e.Operator.Name
                    }),
                    TotalCount = exam.ExamEvents.Count
                }
            });
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
            await UnitOfWorkManager.Current.RollbackAsync();
            return Ok(new WorkflowOutput
            {
                Success = false,
                Error = ex.Message
            });
        }
    }
}
